package org.eclipse.rally.plugin.views;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JOptionPane;

import org.apache.log4j.Logger;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.rally.plugin.Activator;
import org.eclipse.rally.plugin.utils.RallyConstants;
import org.eclipse.rally.plugin.utils.SWTResourceManager;
import org.eclipse.rally.plugin.webservice.RallyMain;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

import com.rallydev.webservice.v1_12.domain.Defect;
import com.rallydev.webservice.v1_12.domain.User;


public class DefectsTabGUI extends ApplicationWindow {
    public static Text text_4;
    public static Group grpSearchDeatails;
    public static Group tableGroup;
    public static int minDefVal = 1;
    public static int maxDefVal = 10;
    public static int defPageNumber = 1;
    public static int totalDefects;
    public static Table table_1;
    public static Table table_4;
    public static List lstDefects;
    static Text text_1;
    static CCombo combo1;
    static CCombo combo2;
    public static TabFolder tabFolder;
    public static TabItem tabItem;
    public static CCombo severityCombo;
    public static CCombo priorityCombo;

    // CCombo stateCombo;
    public static org.eclipse.swt.widgets.List stateCombo;
    public static CCombo submittedCombo;
    public static CCombo ownerCombo;
    public static Text idText;
    public static Text pageNoText;
    public static Text targetBuildText;
    public static Text fixedInText;
    public static Composite composite;
    public final static Composite parent = null;
    static Map refMap;
    public static final List userList = RallyMain.listUsers();
    public static Map userMap;

    static {
        userMap = getUserDisplayName(userList);
    }

    final Display display = Display.getCurrent();
    final Cursor handCursor = new Cursor(display, SWT.CURSOR_HAND);
    final Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
    private Logger logger = Activator.getLogManager().getLogger(DefectsTabGUI.class.getName());
    public DefectsTabGUI() {
        super(null);
    }

    public static void main(String[] args) {
        Display display = new Display();
        Shell shell = new Shell(display);

        TabFolder tabFolder = new TabFolder(shell, SWT.NONE);
        tabFolder.setBounds(0, 0, 950, 500);

        Composite defectcomposite = new Composite(tabFolder, SWT.NONE);
        new DefectsTabGUI().DefectsTabData(tabFolder);

        shell.pack();
        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }

    public void backToDefectPage(TabItem tabitem_1, TabFolder tabFolder) {
        tabFolder = tabFolder;
        tabItem = tabitem_1;

        Composite composite = new Composite(tabFolder, SWT.BORDER);
        tabItem.setControl(composite);
        searchDetailsGroup(composite);
        searchTableGroup(composite, tabFolder);
    }

    public void searchTableGroup(Composite composite, final TabFolder tabFolder) {
        tableGroup = new Group(composite, SWT.BORDER);
        tableGroup.setBackground(SWTResourceManager.getColor(
                SWT.COLOR_LIST_BACKGROUND));
        tableGroup.setBounds(2, 200, 920, 229);

        {
            table_4 = new Table(tableGroup, SWT.BORDER | SWT.FULL_SELECTION);
            table_4.setBounds(2, 10, 910, 183);
            table_4.setHeaderVisible(true);
            table_4.setLinesVisible(true);

            table_4.addListener(SWT.MouseDoubleClick,
                new Listener() {
                    public void handleEvent(Event e) {
                    	logger.info("*****Defect Details Initiated");
                    	setCurssor(tableGroup,true);
                        int id = 2;

                        // String string = "";
                        TableItem[] items = table_4.getItems();

                        //TableItem[] selection = table_4.getSelection();
                        if (items.length == 0) {
                            JOptionPane.showMessageDialog(null,
                                "Nothing to Display", "", 0);
                        } else {
                            TableItem string = null;
                            TableItem[] selection = table_4.getSelection();
                            string = (TableItem) selection[selection.length -
                                1];

                            String strRefrence = (String) refMap.get(string.getText());
                            tableGroup.dispose();

                            try {
                                new DefectDetailGUI().defectDetail(tabFolder,
                                    tabItem, strRefrence, RallyConstants.PAGE_DEFECTS);
                            } catch (Exception e1) {
                                e1.printStackTrace();
                                logger.error(e1);
                            }
                        }
                        setCurssor(tableGroup,false);
                        logger.info("*****Defect Details Finished");
                    }
                });

            {
                TableColumn tblclmnId = new TableColumn(table_4, SWT.BORDER);
                tblclmnId.setWidth(75);
                tblclmnId.setText("ID");
            }

            {
                TableColumn tblclmnName_1 = new TableColumn(table_4, SWT.BORDER);
                tblclmnName_1.setWidth(146);
                tblclmnName_1.setText("Name");
            }

            {
                TableColumn tblclmnSeverity_1 = new TableColumn(table_4,
                        SWT.BORDER);
                tblclmnSeverity_1.setWidth(100);
                tblclmnSeverity_1.setText("Severity");
            }

            {
                TableColumn tblclmnPriority = new TableColumn(table_4,
                        SWT.BORDER);
                tblclmnPriority.setWidth(115);
                tblclmnPriority.setText("Priority");
            }

            {
                TableColumn tblclmnState = new TableColumn(table_4, SWT.BORDER);
                tblclmnState.setWidth(105);
                tblclmnState.setText("State");
            }

            TableColumn tblclmnTargetBuild_1 = new TableColumn(table_4,
                    SWT.BORDER);
            tblclmnTargetBuild_1.setWidth(80);
            tblclmnTargetBuild_1.setText("Target Build");

            TableColumn tblclmnFixedIn = new TableColumn(table_4, SWT.BORDER);
            tblclmnFixedIn.setWidth(78);
            tblclmnFixedIn.setText("Fixed In");

            {
                TableColumn tblclmnTargetBuild = new TableColumn(table_4,
                        SWT.BORDER);
                tblclmnTargetBuild.setWidth(103);
                tblclmnTargetBuild.setText("Submitted By");
            }

            {
                TableColumn tblclmnOwner_2 = new TableColumn(table_4, SWT.BORDER);
                tblclmnOwner_2.setWidth(100);
                tblclmnOwner_2.setText("Owner");
            }

            populateDefectsSearchPage();

            {
                final CLabel clblFirst = new CLabel(tableGroup, SWT.NONE);
                clblFirst.setBackground(SWTResourceManager.getColor(
                        SWT.COLOR_LIST_BACKGROUND));
                clblFirst.setImage(SWTResourceManager.getImage(
                        DefectsTabGUI.class, "/icons/Button-MoveAll.gif"));
                clblFirst.setBounds(540, 199, 49, 19);
                clblFirst.setCursor(handCursor);
                clblFirst.addMouseListener(new MouseAdapter() {
                        @Override
                        public void mouseDown(MouseEvent e) {
                        	setCurssor(clblFirst,true);
                            int x = totalDefects % maxDefVal;
                            int y = (totalDefects / maxDefVal);

                            if (x == 0) {
                                defPageNumber = y;
                            } else {
                                defPageNumber = y + 1;
                            }

                            minDefVal = (defPageNumber * 10) - (maxDefVal - 1);
                            pageNoText.setText(defPageNumber + "");
                            populateDefectsSearchPage();
                            setCurssor(clblFirst,false);
                        }
                    });
            }

            {
                final CLabel clblLast = new CLabel(tableGroup, SWT.NONE);
                // clblLast.setText("");
                clblLast.setBackground(SWTResourceManager.getColor(
                        SWT.COLOR_LIST_BACKGROUND));
                clblLast.setImage(SWTResourceManager.getImage(
                        DefectsTabGUI.class, "/icons/Button-RemoveAll.gif"));
                // clblLast.setBounds(300, 270,50, 17);
                clblLast.setBounds(379, 199, 49, 19);
                clblLast.setCursor(handCursor);
                clblLast.addMouseListener(new MouseAdapter() {
                        @Override
                        public void mouseDown(MouseEvent e) {
                        	setCurssor(clblLast,true);
                            minDefVal = 1;
                            defPageNumber = 1;
                            pageNoText.setText(defPageNumber + "");

                            populateDefectsSearchPage();
                            setCurssor(clblLast,false);
                        }
                    });
            }

            {
                final CLabel clblNext = new CLabel(tableGroup, SWT.NONE);
                // clblPrevious.setText("");
                clblNext.setBackground(SWTResourceManager.getColor(
                        SWT.COLOR_LIST_BACKGROUND));
                clblNext.setImage(SWTResourceManager.getImage(
                        DefectsTabGUI.class, "/icons/FF-enabled.gif"));
                clblNext.setBounds(494, 199, 39, 19);
                clblNext.addMouseListener(new MouseAdapter() {
                        @Override
                        public void mouseDown(MouseEvent e) {
                        	setCurssor(clblNext,true);
                            if (lstDefects.size() == maxDefVal) {
                                minDefVal += maxDefVal;
                                defPageNumber++;
                                pageNoText.setText(defPageNumber + "");
                            }

                            populateDefectsSearchPage();
                            setCurssor(clblNext,false);
                        }
                    });

                clblNext.setCursor(handCursor);
            }

            {
                final CLabel clblPrevious = new CLabel(tableGroup, SWT.NONE);
                // clblNext.setText("");
                clblPrevious.setBackground(SWTResourceManager.getColor(
                        SWT.COLOR_LIST_BACKGROUND));
                clblPrevious.setImage(SWTResourceManager.getImage(
                        DefectsTabGUI.class, "/icons/Button-REW.gif"));
                clblPrevious.setBounds(432, 199, 39, 19);
                clblPrevious.setCursor(handCursor);
                clblPrevious.addMouseListener(new MouseAdapter() {
                        @Override
                        public void mouseDown(MouseEvent e) {
                        	setCurssor(clblPrevious,true);
                            if (minDefVal > 1) {
                                minDefVal -= maxDefVal;
                                defPageNumber--;
                                pageNoText.setText(defPageNumber + "");
                            }

                            populateDefectsSearchPage();
                            setCurssor(clblPrevious,false);
                        }
                    });
            }

            pageNoText = new Text(tableGroup, SWT.BORDER);
            pageNoText.setBounds(629, 199, 39, 19);
            pageNoText.setText(defPageNumber + "");

            {
                Label lblPNo = new Label(tableGroup, SWT.NONE);
                lblPNo.setBackground(SWTResourceManager.getColor(
                        SWT.COLOR_LIST_BACKGROUND));
                lblPNo.setBounds(594, 199, 29, 19);
                lblPNo.setText("P No :");
            }
        }
    }

    public void searchDetailsGroup(Composite composite) {
        grpSearchDeatails = new Group(composite, SWT.BORDER);
        grpSearchDeatails.setBackground(SWTResourceManager.getColor(
                SWT.COLOR_LIST_BACKGROUND));
        grpSearchDeatails.setText("Search Details");
        grpSearchDeatails.setBounds(2, 25, 920, 162);

        {
            {
                Label lblRankid = new Label(grpSearchDeatails, SWT.NONE);
                lblRankid.setBackground(SWTResourceManager.getColor(
                        SWT.COLOR_LIST_BACKGROUND));
                lblRankid.setBounds(10, 47, 27, 13);
                lblRankid.setText("ID:");
                lblRankid.setAlignment(SWT.RIGHT);
            }

            idText = new Text(grpSearchDeatails, SWT.BORDER);
            idText.setBounds(55, 47, 122, 19);

            Label lblName = new Label(grpSearchDeatails, SWT.NONE);
            lblName.setBackground(SWTResourceManager.getColor(
                    SWT.COLOR_LIST_BACKGROUND));
            lblName.setBounds(10, 89, 42, 13);
            lblName.setText("Severity:");
            severityCombo = new CCombo(grpSearchDeatails, SWT.BORDER);
            severityCombo.setText("All");
            severityCombo.setItems(new String[] {
                    "All", "Crash/Data Loss", "Major Problem", "Minor Problem",
                    "Cosmetic"
                });
            severityCombo.setEditable(false);
            severityCombo.setBackground(SWTResourceManager
            		.getColor(SWT.COLOR_LIST_BACKGROUND));
            severityCombo.setBounds(55, 89, 122, 21);

            Label lblPriority_2 = new Label(grpSearchDeatails, SWT.NONE);
            lblPriority_2.setBackground(SWTResourceManager.getColor(
                    SWT.COLOR_LIST_BACKGROUND));
            lblPriority_2.setBounds(210, 47, 39, 13);
            lblPriority_2.setText("Priority:");
            priorityCombo = new CCombo(grpSearchDeatails, SWT.BORDER);
            priorityCombo.setText("All");
            priorityCombo.setItems(new String[] {
                    "All", "Resolve Immediately", "High Attention", "Normal",
                    "Low"
                });
            priorityCombo.setEditable(false);
            priorityCombo.setBackground(SWTResourceManager
            		.getColor(SWT.COLOR_LIST_BACKGROUND));
            priorityCombo.setBounds(255, 45, 109, 21);

            {
                Label lblState_1 = new Label(grpSearchDeatails, SWT.NONE);
                lblState_1.setBackground(SWTResourceManager.getColor(
                        SWT.COLOR_LIST_BACKGROUND));
                lblState_1.setBounds(210, 89, 39, 13);
                lblState_1.setText("State:");
            }

            stateCombo = new org.eclipse.swt.widgets.List(grpSearchDeatails,
                    SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);

            stateCombo.setItems(new String[] {
                    "All", "Submitted", "Open", "As Designed", "Fixed",
                    "Re-open", "Deferred", "Obsolete", "Cannot Reproduce",
                    "Verified", "Closed"
                });
            stateCombo.setSelection(0);
            stateCombo.showSelection();
            stateCombo.setBounds(255, 89, 109, 50);

            {
                Label lblSubmittedBy = new Label(grpSearchDeatails, SWT.NONE);
                lblSubmittedBy.setBackground(SWTResourceManager.getColor(
                        SWT.COLOR_LIST_BACKGROUND));
                lblSubmittedBy.setBounds(628, 47, 65, 13);

                lblSubmittedBy.setText("Submitted By:");
            }

            submittedCombo = new CCombo(grpSearchDeatails, SWT.BORDER);
            submittedCombo.setText("All");
            setUsers(submittedCombo);
            submittedCombo.setEditable(false);
            submittedCombo.setBackground(SWTResourceManager
            		.getColor(SWT.COLOR_LIST_BACKGROUND));
            submittedCombo.setBounds(705, 47, 105, 21);

            {
                Label lblOwner = new Label(grpSearchDeatails, SWT.NONE);
                lblOwner.setBackground(SWTResourceManager.getColor(
                        SWT.COLOR_LIST_BACKGROUND));
                lblOwner.setBounds(630, 89, 75, 21);
                lblOwner.setText("Owner:");
            }

            ownerCombo = new CCombo(grpSearchDeatails, SWT.BORDER);
            ownerCombo.setText("All");
            setUsers(ownerCombo);
            ownerCombo.setEditable(false);
            ownerCombo.setBackground(SWTResourceManager
            		.getColor(SWT.COLOR_LIST_BACKGROUND));
            ownerCombo.setBounds(705, 89, 105, 21);

            {
                Label targetBuild = new Label(grpSearchDeatails, SWT.NONE);
                targetBuild.setBackground(SWTResourceManager.getColor(
                        SWT.COLOR_LIST_BACKGROUND));
                targetBuild.setBounds(412, 47, 60, 13);
                targetBuild.setText("Target Build:");
            }

            targetBuildText = new Text(grpSearchDeatails, SWT.BORDER);
            targetBuildText.setBounds(479, 47, 109, 21);

            {
                Label fixedIn = new Label(grpSearchDeatails, SWT.NONE);
                fixedIn.setBackground(SWTResourceManager.getColor(
                        SWT.COLOR_LIST_BACKGROUND));
                fixedIn.setBounds(412, 89, 65, 13);
                fixedIn.setText("Fixed In:");
            }

            fixedInText = new Text(grpSearchDeatails, SWT.BORDER);
            fixedInText.setBounds(479, 89, 109, 21);

            {
                final Label lbl_Search = new Label(grpSearchDeatails, SWT.NONE);
                lbl_Search.setImage(SWTResourceManager.getImage(
                        DefectsTabGUI.class, "/icons/Search-enabled.gif"));
                lbl_Search.setBounds(805, 123, 58, 23);
                lbl_Search.setBackground(SWTResourceManager.getColor(
                        SWT.COLOR_LIST_BACKGROUND));
                lbl_Search.setCursor(handCursor);
                lbl_Search.addMouseListener(new MouseAdapter() {
                        public void mouseDown(MouseEvent e) {
                        	setCurssor(lbl_Search,true);
                            defPageNumber = 1;
                            minDefVal = 1;
                            pageNoText.setText(defPageNumber + "");
                            populateDefectsSearchPage();
                            System.out.println("inside search button****");
                            setCurssor(lbl_Search,false);
                        }
                    });
            }
        }
    }

    public void DefectsTabData(TabFolder tabFolder) {
        tabFolder = tabFolder;
        tabItem = new TabItem(tabFolder, SWT.NONE);
        tabItem.setText("&Defects");

        Composite composite = new Composite(tabFolder, SWT.BORDER);
        tabItem.setControl(composite);
        searchDetailsGroup(composite);
        searchTableGroup(composite, tabFolder);
    }

    public void populateDefectsSearchPage() {
        try {
            Defect defect = new Defect();

            if (idText.getText().trim().length() > 0) {
                defect.setFormattedID(idText.getText());
            } else {
                defect.setFormattedID(null);
            }

            if (!severityCombo.getText().equalsIgnoreCase("All")) {
                defect.setSeverity(severityCombo.getText());
            } else {
                defect.setSeverity(null);
            }

            if (!priorityCombo.getText().equalsIgnoreCase("All")) {
                defect.setPriority(priorityCombo.getText());
            } else {
                defect.setPriority(null);
            }

            if ((stateCombo != null) && !stateCombo.equals("") &&
                    (stateCombo.getSelectionCount() > 0) &&
                    !getStateValues(stateCombo).equalsIgnoreCase("All")) {
                defect.setState(getStateValues(stateCombo));
            } else {
                defect.setState(null);
            }

            if (targetBuildText.getText().trim().length() > 0) {
                defect.setTargetBuild(targetBuildText.getText());
            } else {
                defect.setTargetBuild(null);
            }

            if (fixedInText.getText().trim().length() > 0) {
                defect.setFixedInBuild(fixedInText.getText());
            } else {
                defect.setFixedInBuild(null);
            }

            if (!submittedCombo.getText().equalsIgnoreCase("All")) {
                defect.setSubmittedBy(getUserMailId(submittedCombo));
            } else {
                defect.setSubmittedBy(null);
            }

            if (!ownerCombo.getText().equalsIgnoreCase("All")) {
                defect.setOwner(getUserMailId(ownerCombo));
            } else {
                defect.setOwner(null);
            }

            RallyMain rallyMain = new RallyMain();

            if (lstDefects != null) {
                lstDefects.clear();
            }

            lstDefects = rallyMain.searchObject(defect, "Defect", minDefVal,
                    maxDefVal);
            table_4.removeAll();
            refMap = new HashMap();

            if ((lstDefects != null) && (lstDefects.size() > 0)) {
                for (int i = 0; i < lstDefects.size(); i++) {
                    TableItem tableItem = new TableItem(table_4, SWT.NONE);
                    Defect defect1 = (Defect) lstDefects.get(i);
                    refMap.put(defect1.getFormattedID(), defect1.getRef());

                    String[] strValue = {
                            defect1.getFormattedID(), defect1.getName(),
                            defect1.getSeverity(), defect1.getPriority(),
                            defect1.getState(), defect1.getTargetBuild(),
                            defect1.getFixedInBuild(),
                            (String) userMap.get(defect1.getSubmittedBy()),
                            (String) userMap.get(defect1.getOwner())
                        
                        };
                    tableItem.setText(strValue);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
        }
    }

    public static void setUsers(CCombo combo) {
        String userName = "";
        List<String> userNameList = new ArrayList<String>();
        //List userList = rallyMain.listUsers();
        System.out.println("size of of the user list***" + userList.size());

        if ((userList != null) && (userList.size() > 0)) {
            userNameList.add("All");

            // strValue = new String[tempLst.size()-1];
            for (int i = 0; i < userList.size(); i++) {
                User user = (User) userList.get(i);

                if (user.getDisplayName() != null) {
                    userName = user.getDisplayName();
                    userNameList.add(userName);
                }
            }

            if ((userNameList != null) && (userNameList.size() > 0)) {
                String[] userStr = userNameList.toArray(new String[0]);
                combo.setItems(userStr);
            }
        }
    }

    public static String getUserMailId(CCombo combo) {
        String userMailId = "";

        if ((userList != null) && (userList.size() > 0)) {
            for (int i = 0; i < userList.size(); i++) {
                User user = (User) userList.get(i);

                if (user.getDisplayName() != null) {
                    if (user.getDisplayName().equalsIgnoreCase(combo.getText())) {
                        userMailId = user.getEmailAddress();
                    }
                }
            }
        }

        return userMailId;
    }

    /*        public static String getUserDisplayName(String mailId) {
                    String usrDisplayName = "";
                    RallyMain rallyMain = new RallyMain();
                    List<String> userNameList = new ArrayList<String>();
                    List userList = rallyMain.listUsers();
                    if (userList != null && userList.size() > 0) {
                            for (int i = 0; i < userList.size(); i++) {
    
                                    User user = (User) userList.get(i);
    
                                    if (user.getEmailAddress() != null) {
                                            if(user.getEmailAddress().equalsIgnoreCase(mailId))
                                                    usrDisplayName =user.getDisplayName();
    
                                    }
                            }
    
    
                    }
                    return usrDisplayName;
    
    
            }*/
    public static Map getUserDisplayName(List userList) {
        userMap = new HashMap();

        if ((userList != null) && (userList.size() > 0)) {
            for (int i = 0; i < userList.size(); i++) {
                User user = (User) userList.get(i);

                if (user.getEmailAddress() != null) {
                    userMap.put(user.getEmailAddress(), user.getDisplayName());
                }
            }
        }

        return userMap;
    }

    public static String getStateValues(org.eclipse.swt.widgets.List comboList) {
        String strVal = "";
        String tempVal = "";
        String[] selection = comboList.getSelection();
        int lastIndex = selection.length - 1;

        for (int i = 0; i < selection.length; i++) {
            tempVal = selection[i];

            if (tempVal.equalsIgnoreCase("All")) {
                strVal = "All";

                break;
            } else {
                if (i == lastIndex) {
                    strVal += selection[i];
                } else {
                    strVal += (selection[i] + ",");
                }
            }
        }

        return strVal;
    }
    public void setCurssor(Control control, boolean b) {
        if (b) {
        	control.setCursor(waitCursor);
        } else {
        	control.setCursor(handCursor);
        }
    }
    
    public static String getUsrName(String emailId) {
      
    	return (String)userMap.get(emailId);
    }
}
